home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / std / c++ / 32 < prev    next >
Encoding:
Text File  |  1996-08-06  |  1.7 KB  |  61 lines

  1. Path: in1.uu.net!bounce-back
  2. Date: 11 Jan 96 15:36:49 GMT
  3. Approved: fjh@cs.mu.oz.au
  4. From: "D. Allan Drummond" <allan.drummond@trilogy.com>
  5. Newsgroups: comp.std.c++
  6. Subject: Re: C++ const semantic
  7. X-Original-Date: Thu, 11 Jan 1996 02:01:22 -0600
  8. Organization: Trilogy
  9. Message-ID: <30F4C3D2.112E@trilogy.com>
  10. References: <9512181324.AA08686@ludo.two-oo-one.fr>
  11. X-Mailer: Mozilla 2.0b3 (WinNT; I)
  12. Cc: std-c++@ncar.ucar.edu, @smtp@trilogy.com
  13. X-Auth: PGPMoose V1.1 PGP comp.std.c++
  14.     iQBFAgUBMPUunuEDnX0m9pzZAQGicwGAl0FUcKqdealWYECPb/6QxGBIw5wlz/M/
  15.     QT9aKZtpHtJpiLy/Kqs+7r0/NbDgqW8s
  16.     =dAO4
  17.  
  18. jlm@two-oo-one.fr wrote:
  19. > In C++ the "A::raz () const" doesn't change the content
  20. > of an A, but it may change its behaviour. Let me take a
  21. > simple example:
  22. > class A {
  23. >     char* text_;
  24. > public:
  25. >     A (const char* t)
  26. >         : text_ (strcpy (new char[strlen(t)+1], t)) {}
  27. >     void raz () const {text_[0] = 0;}
  28. > };
  29.  
  30. While it's true that the behavior of an A may change, all that
  31. const means is that its content does not change -- which you 
  32. appear to recognize.
  33.  
  34. The problem in this case is that you are using char* to mean 
  35. "string", when all it really means is "pointer to char".  A 
  36. better workaround, using the new standard (STL and ANSI string), 
  37. is to say:
  38.  
  39. #include <bstring.h> // HP public-domain string implementation
  40.  
  41. class A {
  42.     string text_;
  43. public:
  44.     A( const char* t ) : text_( t ) {}
  45.     void raz() { text_[0] = 0; }
  46. };
  47.  
  48. Note that raz() now cannot be const - making it const produces a 
  49. compile-time error.
  50.  
  51.  
  52. Allan
  53.  
  54. allan.drummond@trilogy.com
  55. ---
  56. [ comp.std.c++ is moderated.  Submission address: std-c++@ncar.ucar.edu.
  57.   Contact address: std-c++-request@ncar.ucar.edu.  The moderation policy
  58.   is summarized in http://dogbert.lbl.gov/~matt/std-c++/policy.html. ]
  59.